using UnityEngine;
using UnityEditor;
using System.Collections;
using System.Collections.Generic;

[CustomEditor(typeof(DOM))]
public class DOMInspector : Editor
{
	private DOM dom;
	private int lastNode = 0;
	private int currentNode = 0;
	private bool foldDefaultInspector = false;
	
	public override void OnInspectorGUI()
	{
		dom = (DOM)target;
		
		lastNode = currentNode;
		currentNode = EditorGUILayout.IntSlider("Current: ", currentNode+1, 1, dom.allSupplies.Count) - 1;
		
		for(int i = 0; i < dom.allSupplies.Count; i++)
		{
			if(i == currentNode)
			{
				GUI.backgroundColor = Color.green;
				if(lastNode != currentNode)
				{
					dom.allSupplies[lastNode].show = false;
					dom.allSupplies[currentNode].show = true;
					lastNode = currentNode;
				}
			}
			
			EditorGUILayout.BeginVertical(new GUIStyle("box"));
			
			GUI.backgroundColor = Color.white;
			
			EditorGUILayout.BeginHorizontal();
			
			string title = " ";
			if (dom.allSupplies[i].prefab != null)
			{
				title = dom.allSupplies[i].prefab.name;
			}
			dom.allSupplies[i].show = EditorGUILayout.Foldout(dom.allSupplies[i].show, (i+1) + ". " + title);
			
			GUILayout.FlexibleSpace();
			if(GUILayout.Button("Up"))
			{
				if(i > 0)
				{
					dom.allSupplies.Insert(i-1, dom.allSupplies[i]);
					dom.allSupplies.RemoveAt(i+1);
					currentNode-=1;
				 	EditorUtility.SetDirty(dom);
				}
			}
			if(GUILayout.Button("Down"))
			{
				if(i+1 < dom.allSupplies.Count)
				{
					dom.allSupplies.Insert(i+2, dom.allSupplies[i]);
					dom.allSupplies.RemoveAt(i);
					
					if(i == currentNode)
					{
						currentNode+=1;
					}
					
				 	EditorUtility.SetDirty(dom);
				}
			}
			if(GUILayout.Button("Delete"))
			{
				dom.allSupplies.RemoveAt(i);
				
				if(dom.allSupplies.Count > 0)
				{
					if(i == currentNode-1)
					{
						currentNode-=1;
						dom.allSupplies[i-1].show = true; 
					}
					EditorUtility.SetDirty(dom);
					return;
				}
				else
				{
					dom.allSupplies.Add(new Supply());
				}
			}
			
			EditorGUILayout.EndHorizontal();
	
			if(dom.allSupplies.Count > 0)
			{
				if(dom.allSupplies[i].show)
				{
					EditorGUILayout.Space();
					dom.allSupplies[i].prefab = EditorGUILayout.ObjectField("Prefab: ", dom.allSupplies[i].prefab, typeof(GameObject)) as GameObject;
					dom.allSupplies[i].count = EditorGUILayout.IntField("Count: ", dom.allSupplies[i].count);
					dom.allSupplies[i].isChildren = EditorGUILayout.Toggle("Is Children: ", dom.allSupplies[i].isChildren);
				}
			}
			EditorGUILayout.Space();
			EditorGUILayout.EndVertical();
		}
		
		if(GUILayout.Button("Add Stock"))
		{
			dom.allSupplies.Add(new Supply());
		}
		
		if(foldDefaultInspector = EditorGUILayout.Foldout(foldDefaultInspector, "DefaultInspector"))
		{
			DrawDefaultInspector();
		}
	}
}
